package com.ecourseapp.NativeForRN.wechat;

/**
 * @author 文庆
 * @date 2018/8/9.
 * @description
 */


import android.util.Xml;
import android.widget.Toast;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.xmlpull.v1.XmlPullParser;

import java.io.StringReader;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class WxpayModule extends ReactContextBaseJavaModule {

    private IWXAPI api;
    public static String APP_ID = "";
    public static Promise promise = null;

    WxpayModule(ReactApplicationContext reactContext) {
        super(reactContext);
        api = WXAPIFactory.createWXAPI(reactContext, null);
    }
    @Override
    public String getName() {
        return "Wxpay";
    }

    @ReactMethod
    public void showHello() {
        String name = "hello wechat";
        Toast.makeText(getReactApplicationContext(), name, Toast.LENGTH_LONG).show();
    }

    @ReactMethod
    public void registerApp(String APP_ID) { // 向微信注册
        WxpayModule.APP_ID = APP_ID;
        api.registerApp(APP_ID);
    }

    @ReactMethod
    public void pay(final String order, Promise promise) {
        WxpayModule.promise = promise;
        PayReq request = new PayReq();


//        request.appId = "wxed051da706bfc9c6";
//        request.partnerId ="1493917502";
//        request.prepayId= "wx0912442440097873dd25a65c1403834908";
//        request.packageValue ="Sign=WXPay";
//        request.nonceStr= "a3b36cb25e2e0b93b5f334ffb4e4064e";
//        request.timeStamp= "1533789340";
//        request.sign="F7CE1475877C71C5F26EC3BDB556FF82";

//        request.appId = order.getString("appid");
//        request.partnerId = order.getString("partnerid");
//        request.prepayId= order.getString("prepayid");
//        request.packageValue = order.getString("package");
//        request.nonceStr= order.getString("noncestr");
//        request.timeStamp= "1533789340";
//        request.sign= order.getString("sign");



        genPayReq(request, decodeXml(order),"6D47B8C013BCA0CD9C074C0ADE837421");
        api.sendReq(request);
    }

    @ReactMethod
    public void isSupported(Promise promise) { // 判断是否支持调用微信SDK
        boolean isSupported = api.isWXAppInstalled();
        promise.resolve(isSupported);
    }



    public Map<String, String> decodeXml(String content) {

        try {
            Map<String, String> xml = new HashMap<>();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(content));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {

                String nodeName = parser.getName();
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:

                        if (!"xml".equals(nodeName)) {
                            //实例化student对象
                            xml.put(nodeName, parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                    default:
                        break;
                }
                event = parser.next();
            }

            return xml;
        } catch (Exception e) {
        }
        return null;
    }
    private String genNonceStr() {
        Random random = new Random();
        return getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }
    public final static String getMessageDigest(byte[] buffer) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(buffer);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }
    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    private void genPayReq(PayReq req, Map<String, String> result, String apiKey) {
        req.appId =  "wxed051da706bfc9c6";
        req.partnerId = "1493917502";
        req.prepayId = result.get("prepay_id");
        req.packageValue = "Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(genTimeStamp());

        StringBuilder sb = new StringBuilder(100);
        sb.append("appid").append('=').append(req.appId).append('&');
        sb.append("noncestr").append('=').append(req.nonceStr).append('&');
        sb.append("package").append('=').append(req.packageValue).append('&');
        sb.append("partnerid").append('=').append(req.partnerId).append('&');
        sb.append("prepayid").append('=').append(req.prepayId).append('&');
        sb.append("timestamp").append('=').append(req.timeStamp).append('&');
        sb.append("key=").append(apiKey);
        req.sign = getMessageDigest(sb.toString().getBytes()).toUpperCase();
    }
}